package com.ruoyi.api.web;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.shop.domain.ShopUserOpenid;
import com.ruoyi.shop.service.IShopUserOpenidService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Alan Zhang
 * @Date 2021/9/25 11:25
 * API基础类
 */
public class ApiBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private IShopUserOpenidService shopUserOpenidService;


    public ShopUserOpenid shopUserIdByToken(){
        String token = getToken();
        ShopUserOpenid shopUserOpenid = shopUserOpenidService.selectShopUserOpenidBySessionKey(token);
        if(shopUserOpenid == null || shopUserOpenid.getUserId() == null){
            throw new BusinessException("用户不存在");
        }
        return shopUserOpenid;
    }

    /**
     * 获取request
     */
    public HttpServletRequest getRequest()
    {
        return ServletUtils.getRequest();
    }

    /**
     * 获取response
     */
    public HttpServletResponse getResponse()
    {
        return ServletUtils.getResponse();
    }


    public String getToken(){
        String token = getRequest().getHeader("token");
        logger.info("token---------"+token);
        return token;
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }
}
